package com.zjt.takeoutproject.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjt.takeoutproject.common.R;
import com.zjt.takeoutproject.dto.DishDto;
import com.zjt.takeoutproject.dto.SetmealDto;
import com.zjt.takeoutproject.entity.*;
import com.zjt.takeoutproject.service.CategoryService;
import com.zjt.takeoutproject.service.DishService;
import com.zjt.takeoutproject.service.SetmealDishService;
import com.zjt.takeoutproject.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2023-06-13
 */
@Slf4j
@RestController
@Api(tags = "套餐相关接口")
@RequestMapping("/setmeal")
public class SetmealController {

    @Resource
    private SetmealService setmealService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private SetmealDishService setmealDishService;

    @Resource
    private DishService dishService;

    //新增套餐
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息：{}",setmealDto);

        //操作setmeal表
        setmealService.saveWithDish(setmealDto);
        //操作setmealDish关系表
        setmealDishService.saveWithDish(setmealDto);
        return R.success("套餐新增成功");
    }

    //套餐分页查询
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询套餐名
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);
        //将分类id改为分类名称
        //1.拷贝分页基本信息
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        //2.setDto记录的内容
        List<SetmealDto> list = new ArrayList<>();

        List<Setmeal> records = pageInfo.getRecords();
        for (Setmeal record : records) {
            SetmealDto setmealDto = new SetmealDto();
            Long categoryId = record.getCategoryId();
            BeanUtils.copyProperties(record,setmealDto);
            //根据id查分类名
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            list.add(setmealDto);
        }

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    //批量删除套餐
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        //删除套餐需要删除套餐表及关联菜品表
        //1.删除套餐，判断是否能删除
        setmealService.removeSetmealById(ids);
        //2.删除套餐成功后删除关联菜品表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        //逻辑删除，故不删除关联表
//        setmealDishService.remove(queryWrapper);
        return R.success("套餐删除成功");
    }

    //批量停售套餐
    @PostMapping("status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("status:{}",status);
        log.info("dishDto:{}",ids);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(ids !=null,Setmeal::getId,ids);
        //根据传入的id集合进行批量查询
        List<Setmeal> list = setmealService.list(queryWrapper);
        //修改状态
        for (Setmeal setmeal : list) {
            if (setmeal != null){
                setmeal.setStatus(status);
                setmealService.updateById(setmeal);
            }
        }
        return R.success("售卖状态修改成功");
    }

    //用户端根据条件查询套餐信息
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //构造查询条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        //起售状态
        queryWrapper.eq(Setmeal::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime).orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 点击查看套餐中的菜品
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable("id") Long SetmealId) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, SetmealId);
        //获取套餐里面的所有菜品  这个就是SetmealDish表里面的数据
        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        List<DishDto> dishDtos = list.stream().map((setmealDish) -> {
            DishDto dishDto = new DishDto();
            //将套餐菜品关系表中的数据拷贝到dishDto中
            BeanUtils.copyProperties(setmealDish, dishDto);
            //这里是为了把套餐中的菜品的基本信息填充到dto中，比如菜品描述，菜品图片等菜品的基本信息
            String dishId = setmealDish.getDishId();
            Dish dish = dishService.getById(new Long(dishId));
            //将菜品信息拷贝到dishDto中
            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtos);
    }

}
